<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20">
      <el-col :span="5">
        <div>
              <span style="color:black">外呼总数: {{callStatusGroup.count ? callStatusGroup.count : 0}}</span>  <br> 
              <span style="color:fuchsia">暂未拨打: {{callStatusGroup.none ? callStatusGroup.none : 0}}</span> <br> 
              <span style="color:blueviolet">正排队中: {{callStatusGroup.queued ? callStatusGroup.queued : 0}}</span> <br> 
              <span style="color:blueviolet">正进行中: {{callStatusGroup.inprogress ? callStatusGroup.inprogress : 0}}</span> <br> 
              <span style="color:green">已接通一: {{callStatusGroup.completed ? callStatusGroup.completed : 0}}</span> <br>
        </div>
      </el-col>
      <el-col :span="5">
        <div>
          <span style="color:red">未接听一: {{callStatusGroup.noanswer ? callStatusGroup.noanswer : 0}}</span>  <br>     
          <span style="color:red">呼叫失败: {{callStatusGroup.failed ? callStatusGroup.failed : 0}}</span>  <br> 
          <span style="color:red">呼叫忙线: {{callStatusGroup.busy ? callStatusGroup.busy : 0}}</span> <br>  
          <span style="color:red">外呼异常: {{callStatusGroup.error ? callStatusGroup.error : 0}}</span>
        </div>
      </el-col>
      <el-col :span="5">
        <div>
            <span style="color:black">短信总数: {{smsStatusGroup.count ? smsStatusGroup.count : 0}}</span> <br> 
            <span style="color:fuchsia">暂未发送: {{smsStatusGroup.none ? smsStatusGroup.none : 0}}</span> <br>   
            <span style="color:green">已送达一: {{(smsStatusGroup.sent ? smsStatusGroup.sent : 0) + (smsStatusGroup.delivered ? smsStatusGroup.delivered : 0)}}</span> <br>
            <span style="color:red">发送失败: {{(smsStatusGroup.failed ? smsStatusGroup.failed : 0) + (smsStatusGroup.undelivered ? smsStatusGroup.undelivered : 0)}}</span> <br> 
            <span style="color:red">短信异常: {{smsStatusGroup.error ? smsStatusGroup.error : 0}}</span>
        </div>
      </el-col>
      <el-col :span="3">
        <div>
              <span style="color:fuchsia">自动外呼: {{autoCallSwitch ? "开启" : "关闭"}}</span> <br>
              <span style="color:green">自动短信: {{autoSmsSwitch ? "开启" : "关闭"}}</span>  <br>
              <span style="color:cornflowerblue">自动分析: {{autoAnalysisSwitch ? "开启" : "关闭"}}</span>
        </div>
      </el-col>
      </el-row>
    </el-card>


    <el-card class="box-card" style="margin-top: 6px">
      <el-form ref="selectform" :inline="true" :model="selectform" class="demo-form-inline ManagementClass">

        <el-form-item label="被叫号码">
          <el-input v-model="selectform.toPhone" size="mini" clearable placeholder="请输入被叫号码"
                    prefix-icon="el-icon-search"
                    class="AuthorityInput managementBtn"/>
        </el-form-item>

        <el-form-item label="主叫号码">
          <el-input v-model="selectform.fromPhone" size="mini" clearable placeholder="请输入主叫号码"
                    prefix-icon="el-icon-search"
                    class="AuthorityInput managementBtn"/>
        </el-form-item>

        <el-form-item label="电话状态">
          <el-select v-model="selectform.status" clearable placeholder="请选择">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="短信状态">
          <el-select v-model="selectform.smsStatus" clearable placeholder="请选择">
            <el-option
              v-for="item in smsStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="按键事件">
          <el-select v-model="selectform.callCustomerTrigger" clearable placeholder="请选择">
            <el-option
              v-for="item in callCustomerTriggerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="mini" @click="selectSubmit()">查询</el-button>
          <el-button type="info" size="mini" @click="selectResetForm('selectform')">重置</el-button>
          <el-button type="success" size="mini" @click="importCallInfoVisible = true">导入号码</el-button>
          <el-button type="danger" size="mini" @click="openFileBtn(0)">配置文件</el-button>
          <el-button type="warning" size="mini" @click="batchDeleteBtn()">批量删除</el-button>
          <el-button type="warning" size="mini" style="background-color: #a509e3;border-color:#a509e3;" @click="autoSwitchBtn(autoCallSwitch,null,null)">自动外呼</el-button>
          <el-button type="warning" size="mini" style="background-color: blue;border-color:blue" @click="autoSwitchBtn(null,autoSmsSwitch,null)">自动短信</el-button>
          <el-button type="warning" size="mini" style="background-color:crimson;border-color:crimson" @click="autoSwitchBtn(null,null,autoAnalysisSwitch)">自动分析</el-button>
          <el-button type="warning" size="mini" v-loading="exportDataLoading" style="background-color:lightseagreen;border-color:lightseagreen" @click="exportDataBtn()">导出数据</el-button>
          <!-- <el-button type="danger" style="background-color: #a509e3;border-color:#a509e3;" size="mini" @click="startCallBtn(null)">批量外呼</el-button>
          <el-button type="danger" style="background-color: blue;border-color:blue" size="mini" @click="startCallBackBtn(null)">批量外呼回调</el-button>
          <el-button type="danger" style="background-color: #a509e3;border-color:#a509e3;" size="mini" @click="startSMSBtn(null)">批量短信</el-button>
          <el-button type="danger" style="background-color: blue;border-color:blue" size="mini" @click="startSMSBackBtn(null)">批量短信回调</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 6px">

      <el-table v-loading="loading"
                ref="multipleTable"
                :data="tableData" border size="mini" style="width: 100%"
                :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'left' }"
                :row-key="getRowKey"
                @selection-change="handleSelectionChange">

        <el-table-column type="selection" :reserve-selection="true" width="30">
        </el-table-column>

        <el-table-column prop="index" label="序号" width="55">
        </el-table-column>

        <el-table-column  label="号码" width="160">
          <template slot-scope="scope">
            <div>被叫:{{ scope.row.toPhone  }}</div>
            <div>主叫:{{ scope.row.fromPhone  }}</div>
            <div>录音:{{ scope.row.record === 0 ? "关闭":"开启" }}</div>
            <div>创建:{{ scope.row.createTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="200">
          <template slot-scope="scope">
            <div :style="getStatusStyle(scope.row.status)" v-if="scope.row.callTime !== '1970-01-01 00:00:00'">电话状态:{{ mapStatus(scope.row.status) }}</div>
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'" style="color: lightseagreen;">通话时长:{{ scope.row.duration }}</div>
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'" style="color: #a509e3;">录音时长:{{ scope.row.recordingDuration }}</div>
            <div :style="getStatusStyle(scope.row.smsStatus)" v-if="scope.row.smsTime !== '1970-01-01 00:00:00'">短信状态:{{ mapSmsStatus(scope.row.smsStatus) }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="callTime" label="操作时间" width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'">发起外呼:{{ scope.row.callTime == '2008-08-08 00:00:00' ? '' : scope.row.callTime }}</div>
            <div v-if="scope.row.callbackTime !== '1970-01-01 00:00:00'">外呼回调:{{ scope.row.callbackTime == '2008-08-08 00:00:00' ? '' : scope.row.callbackTime }}</div>
            <div v-if="scope.row.smsTime !== '1970-01-01 00:00:00'">发起短信:{{ scope.row.smsTime == '2008-08-08 00:00:00' ? '' : scope.row.smsTime }}</div>
            <div v-if="scope.row.smsbackTime !== '1970-01-01 00:00:00'">短信回调: {{ scope.row.smsbackTime == '2008-08-08 00:00:00' ? '' : scope.row.smsbackTime }}</div>
          </template>
        </el-table-column>

        <el-table-column  label="通话流程" width="320" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'">通话暂停:{{ scope.row.callPause }}</div>
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'">客户按键:{{ scope.row.callCustomerTrigger }}</div>
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'">录音地址: {{ scope.row.recordLocalUrl }}</div>
            <div v-if="scope.row.smsTime !== '1970-01-01 00:00:00'">短信触发:{{ scope.row.smsTrigger }}</div>
          </template>
        </el-table-column>

        <el-table-column  label="话术内容" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-if="scope.row.callTime !== '1970-01-01 00:00:00'" style="color: red;">外呼话术:{{ scope.row.welcomeText }}</div>
            <div v-if="scope.row.smsTime !== '1970-01-01 00:00:00'" style="color: red;">短信内容:{{ scope.row.smsText }}</div>
            <div v-if="scope.row.remark !== ''">备注:{{ scope.row.remark }}</div>
            <div v-if="scope.row.analysisResult !== ''" style="color: deeppink;">录音文本:{{ scope.row.analysisResult }}</div>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button style="margin-top: 2px;" type="success" size="mini" :disabled="scope.row.callSid !== '' " @click="startCallBtn(scope.row.id)">发起外呼</el-button>
            <el-button style="margin-top: 2px;" type="success" size="mini" :disabled="scope.row.recordingSid !== ''" @click="startCallBackBtn(scope.row.id)">通话回执</el-button><br/>
            <el-button style="margin-top: 2px;" type="primary" size="mini" :disabled="scope.row.recordLocalUrl === ''" @click="audioPlay(scope.row.recordLocalUrl)">播放录音</el-button>
            <el-button style="margin-top: 2px;" type="primary" size="mini"  @click="viewCallback(scope.row)">查看回调</el-button><br/>
            <el-button style="margin-top: 2px;" type="danger" size="mini" :disabled="scope.row.smsSid !== '' || scope.row.smsText === ''" @click="startSMSBtn(scope.row.id)">发起短信</el-button>
            <el-button style="margin-top: 2px;" type="danger" size="mini" :disabled="scope.row.smsSid === '' || scope.row.smsText === ''" @click="startSMSBackBtn(scope.row.id)">短信回执</el-button><br/>
            <el-button style="margin-top: 2px;border-color:darkturquoise;background-color: darkturquoise;" type="danger" size="mini"  :disabled="scope.row.recordingSid === ''" @click="analysisRecordingBtn(scope.row.id)">录音分析</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <pagination :pager="pager" @search="search"/>

    <!-- 显示回调数据的对话框 -->
    <el-dialog title="查看回调" :visible.sync="callbackDialogVisible">
      <el-form label-position="top">
        <el-form-item label="外呼请求">
          <pre v-html="callResponse"></pre>
        </el-form-item>
        <el-form-item label="外呼回调">
          <pre v-html="callBackResponse"></pre>
        </el-form-item>
        <el-form-item label="短信请求">
          <pre v-html="smsResponse"></pre>
        </el-form-item>
        <el-form-item label="短信回调">
          <pre v-html="smsBackResponse"></pre>
        </el-form-item>
        <el-form-item label="语音分析">
          <pre v-html="analysisResult"></pre>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="导入号码" :visible.sync="importCallInfoVisible">

      <el-form :label-position="labelPosition" :model="importCallInfoForm" label-width="80px">
        <el-form-item label="主叫号码">
          <el-input
            placeholder="请输入主叫号码 支持多个 英文状态下的“逗号”分隔（需要带区号 参考：+12097634840,+12097634840,+12097634840）如果未输入,则取配置文件里面的"
            v-model="importCallInfoForm.fromPhone"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="通话暂停">
          <el-input-number v-model="importCallInfoForm.callPause" size="mini" :min="10" :max="180"></el-input-number>
          【播完·外呼话术后·多少秒自动挂断】
        </el-form-item>
        <el-form-item label="外呼话术">
          <el-input type="textarea"
                    size="mini"
                    v-model="importCallInfoForm.welcomeText"
                    placeholder="请输入外呼话术-接通后自动播放的话术"></el-input>
        </el-form-item>
        <el-form-item label="通话录音">
          <el-switch
            v-model="importCallInfoForm.record"
            :active-value="1"
            active-text="开启"
            :inactive-value	="0"
            inactive-text="关闭">
          </el-switch>
        </el-form-item>
        <el-form-item label="按键触发">
          <el-input-number v-model="importCallInfoForm.smsTrigger" size="mini" :min="-1" :max="9"></el-input-number>
          【语音按键触发短信发送 -1是不触发 0-9为按键触发】
        </el-form-item>
        <el-form-item label="短信内容">
          <el-input type="textarea"
                    size="mini"
                    v-model="importCallInfoForm.smsText"
                    placeholder="请输入短信内容"></el-input>
        </el-form-item>
        <el-form-item label="被叫号码">
          <el-input type="textarea"
                    v-model="importCallInfoForm.toPhoneLine"
                    :autosize="{ minRows: 5, maxRows: 10}"
                    placeholder="请输入被叫号码（需要带区号 参考：+12097634840）一行一个号码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="importCallInfoVisible = false">取 消</el-button>
          <el-button type="primary" @click="importCallInfoBtn()">确 定</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>


<style scoped>
/* 调整 el-form 的布局，使表单项左对齐 */
.el-form {
  text-align: left;
  display: block;
}

/* 使每个表单项的标签左对齐 */
.el-form-item__label {
  text-align: left !important;
  width: auto; /* 自动宽度 */
  margin-right: 5px; /* 控制标签和输入框之间的间距 */
}

/* 使表单项的输入框左对齐 */
.el-form-item__content {
  display: inline-block;
}

/* 控制预格式化文本显示的紧凑样式 */
pre {
  font-size: 12px;  /* 减小字体 */
  line-height: 1.2;  /* 缩小行高 */
  margin: 0;  /* 去掉上下的默认外边距 */
  padding: 0;  /* 去掉内边距 */
  white-space: pre-wrap;  /* 保持换行符，但允许换行 */
  word-break: break-word;  /* 长词换行 */
  overflow-wrap: break-word; /* 避免长文本溢出 */
}

</style>

<script>
import {batchDelete,page,groupBy,openFile,exportData} from "../../api/common";
import {importCallInfo} from "../../api/call"
import {startCall,startCallBack,startSMS,startSMSBack,autoSwitch} from "../../api/signalWire"
import pagination from "@/components/pagination.vue";

export default {
  components: {
    pagination,
  },
  data() {
    return {
      tableName: "signalWireCallInfo",
      pager: {
        pageSize: 20,
        currentPage: 1,
        totalPage: 0,
      },
      selectform: {
        toPhone: "",
        fromPhone: "",
        status:"",
        smsStatus:"",
        callCustomerTrigger:""
      },
      loading: false,
      multipleSelection: [],
      tableData: [],
      //导出数据
      exportDataLoading: false,
      //自动外呼
      autoCallSwitch:false,
      //自动短信
      autoSmsSwitch:false,
      //自动分析
      autoAnalysisSwitch:false,
      //播放录音
      audio: null,
      //导入号码
      labelPosition: 'right',
      importCallInfoVisible: false,
      importCallInfoLoading: false,
      importCallInfoForm: {
        tableName: "",//表格名
        toPhoneLine: "",//被叫号码 转行符切割
        toPhoneList: [],//被叫号码
        fromPhone: "",//主叫号码
        welcomeText: "",//语音话术
        record: 1,//开启录音  0关闭 1开启
        callPause: 15,//播放语音后暂停时长
        smsText:"",//短信内容
        smsTrigger:-1,//短信触发按键号码
      },
      //电话状态
      statusOptions: [{
          value: 'none',
          label: '暂未拨打'
        }, {
          value: 'in-progress',
          label: '进行中'
        }, {
          value: 'completed',
          label: '已接通'
        }, {
          value: 'failed',
          label: '呼叫失败'
        }, {
          value: 'busy',
          label: '呼叫忙线'
        },{
          value: 'no-answer',
          label: '未接听'
        },{
          value: 'queued',
          label: '排队中'
        }
      ],
      //短信状态
      smsStatusOptions: [{
          value: 'none',
          label: '暂未发送'
        }, {
          value: 'sent',
          label: '短信已发送'
        }, {
          value: 'delivered',
          label: '短信已送达'
        }, {
          value: 'failed',
          label: '发送失败'
        }, {
          value: 'undelivered',
          label: '短信未送达'
        }],
      //按键事件
      callCustomerTriggerOptions: [
        {
          value: '未触发',
          label: '未触发'
        }, {
          value: '触发',
          label: '触发'
        }],
        //查看回调
        callbackDialogVisible: false, // 控制回调弹窗显示
        callResponse: '',
        callBackResponse: '',
        smsResponse: '',
        smsBackResponse: '',
        analysisResult:'',
        //外呼状态分组
        callStatusGroup: {},
        //短信状态分组
        smsStatusGroup: {},
    };
  },
  created() {
    this.getInfo();
    this.groupByBtn();
    this.autoSwitchBtn(null,null,null);
  },
  methods: {
    search() {
      this.getInfo();
      this.groupByBtn();
      this.autoSwitchBtn(null,null,null);
    },
    getInfo() {
      this.loading = true;
      page(this.parameter(null)).then((res) => {
        this.loading = false;
        res.data.forEach((item, index) => {
          item.index = index + 1 + (this.pager.currentPage - 1) * this.pager.pageSize;
          return item;
        });
        this.tableData = res.data;
        this.pager.totalPage = res.total;
        if (res.code === -1) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },

    // 搜索重置
    selectResetForm() {
      this.pager.currentPage = 1;
      this.selectform = {
        toPhone: "",
        fromPhone: "",
        status: "",
        smsStatus: "",
        callCustomerTrigger:""
      };
      this.multipleSelection = [];
      this.search();
    },

    //搜索条件
    parameter(groupField) {
      return {
        current: this.pager.currentPage,
        size: this.pager.pageSize,
        dictValues: this.selectform,
        groupField: groupField,
        tableName: this.tableName,
      };
    },

    // 搜索
    selectSubmit() {
      this.pager.currentPage = 1;
      this.search();
      this.multipleSelection = [];
    },

    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("多选：", this.multipleSelection.length)
    },

    // 指定一个key标识这一行的数据
    getRowKey(row) {
      return row.id
    },
  // 根据状态返回不同颜色
  getStatusStyle(status) {
    //异常状态
    const errorStatuses1 = ['failed','undelivered', 'no-answer', 'busy', 'timeout']; 
    if (errorStatuses1.includes(status)){
        return { color: 'red', backgroundColor: '#f8d7da' }
      }

      const errorStatuses2 = ['completed','in-progress','sent','delivered']; 
    if (errorStatuses2.includes(status)){
        return { color: 'green', backgroundColor: '#d4edda' }
      }

      const errorStatuses3 = ['none']; 
    if (errorStatuses3.includes(status)){
        return { color: 'blue', backgroundColor: '#cce5ff'  }
      }

      const errorStatuses4 = ['queued'];
      if (errorStatuses4.includes(status)){
      return { color: 'white', backgroundColor: '#f78fa7' }
    }
      return { color: 'black', backgroundColor: 'white' }; // 默认颜色
  },

      // 映射电话状态
  mapStatus(status) {
    const statusMap = {
      'none': '暂未拨打',
      'in-progress': '已接通',
      'completed': '已完成',
      'failed': '呼叫失败',
      'busy': '呼叫忙线',
      'no-answer': '未接听',
      'queued': '排队中',
    };
    return statusMap[status] || '未知状态';  // 默认返回 '未知状态'
  },

  // 映射短信状态
  mapSmsStatus(smsStatus) {
    const smsStatusMap = {
      'none': '暂未发送',
      'sent': '已成功发送',
      'delivered': '已送达目标',
      'failed': '发送失败',
      'undelivered': '未能送达',
    };
    return smsStatusMap[smsStatus] || '未知状态';  // 默认返回 '未知状态'
  },

  //分组查询
  groupByBtn() {
    groupBy(this.parameter("status")).then((res) => {
      if (res.code === -1) {
        this.$message({
          showClose: true,
          message: res.message,
          type: "error",
        });
      } else {
        this.callStatusGroup = res.data;
      }
    })
    groupBy(this.parameter("smsStatus")).then((res) => {
      if (res.code === -1) {
        this.$message({
          showClose: true,
          message: res.message,
          type: "error",
        });
      } else {
        this.smsStatusGroup = res.data;
      }
    })
  },
  exportDataBtn(){
    this.exportDataLoading = true;
    exportData(this.parameter(null)).then((res) => {
      this.exportDataLoading = false;
      if (res.code === -1) {
        this.$message({
          showClose: true,
          message: res.message,
          type: "error",
        });
      } else {
        this.$message({
          showClose: true,
          message: res.data,
          type: "success",
        });
      }
    })
  },
  //autoSwitch
  autoSwitchBtn(autoCallSwitch1,autoSmsSwitch2,autoAnalysisSwitch3) {
    if (autoCallSwitch1 != null){
      autoCallSwitch1 = this.autoCallSwitch ? false:true;
    }
    if (autoSmsSwitch2 != null){
      autoSmsSwitch2 = this.autoSmsSwitch ? false:true;
    }
    if (autoAnalysisSwitch3 != null){
      autoAnalysisSwitch3 = this.autoAnalysisSwitch ? false:true;
    }
    let autoSwitchRest = {
      autoCallSwitch: autoCallSwitch1,
      autoSmsSwitch: autoSmsSwitch2,
      autoAnalysisSwitch: autoAnalysisSwitch3
    }
    console.log(JSON.stringify(autoSwitchRest));
    autoSwitch(autoSwitchRest).then((res) => {
      if (res.code === -1) {
        this.$message({
          showClose: true,
          message: res.message,
          type: "error",
        });
      } else {
        this.autoCallSwitch = res.data.autoCallSwitch;
        this.autoSmsSwitch = res.data.autoSmsSwitch;
        this.autoAnalysisSwitch = res.data.autoAnalysisSwitch;
      }
    })
  },
    //播放录音
    audioPlay(recordLocalUrl) {
      //在调用时如果有音频在播放，先做暂停操作，将audio置空
      if (this.audio !== null) {
        // 暂停录音
        this.audio.pause();
        this.audio = null;
      }
      //然后再new Audio创建新的音频
      this.audio = new Audio(recordLocalUrl);
      // 不循环播放
      this.audio.loop = false;
      // 播放录音     
      this.audio.play();
    },
    //发起外呼
    startCallBtn(id) {
      let ids = id ? [id] : this.multipleSelection.map(item => item.id);
      if (ids.length === 0) {
        this.$message.error('请先选择需要操作的记录');
        return;
      }
      this.$confirm('此操作将发起外呼操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            startCall({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.search();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //外呼回调
    startCallBackBtn(id) {
      let ids = id ? [id] : this.multipleSelection.map(item => item.id);
      if (ids.length === 0) {
        this.$message.error('请先选择需要操作的记录');
        return;
      }
      this.$confirm('此操作将发起外呼回调操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            startCallBack({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.search();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },

      //发送短信
      startSMSBtn(id) {
      let ids = id ? [id] : this.multipleSelection.map(item => item.id);
      if (ids.length === 0) {
        this.$message.error('请先选择需要操作的记录');
        return;
      }
      this.$confirm('此操作将发送短信操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          startSMS({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.search();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //分析录音
      analysisRecordingBtn(id) {
      let ids = id ? [id] : this.multipleSelection.map(item => item.id);
      if (ids.length === 0) {
        this.$message.error('请先选择需要操作的记录');
        return;
      }
      this.$confirm('此操作将进行录音转文本分析操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          analysisRecording({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.search();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //短信回调
      startSMSBackBtn(id) {
      let ids = id ? [id] : this.multipleSelection.map(item => item.id);
      if (ids.length === 0) {
        this.$message.error('请先选择需要操作的记录');
        return;
      }
      this.$confirm('此操作将发起短信回调操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          startSMSBack({
              "tableName": this.tableName,
              "fieldName": "id",
              "fieldValueList": ids
            }).then((res) => {
              this.search();
              this.multipleSelection = [];
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: res.data,
                type: "success",
              });
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },


        // 查看回调
    viewCallback(row) {
      if (row.callResponse === ""){
        this.callResponse = '{}'
      }else{
        this.callResponse = row.callResponse
      }
      if (row.callBackResponse === ""){
        this.callBackResponse = '{}'
      }else{
        this.callBackResponse = row.callBackResponse
      }
      if (row.smsResponse === ""){
        this.smsResponse = '{}'
      }else{
        this.smsResponse = row.smsResponse
      }
      if (row.smsBackResponse === ""){
        this.smsBackResponse = '{}'
      }else{
        this.smsBackResponse = row.smsBackResponse
      }
      if (row.analysisResult === ""){
        this.analysisResult = '{}'
      }else{
        this.analysisResult = row.analysisResult
      }
      this.callResponse = JSON.stringify(JSON.parse(this.callResponse), null, 2);
      this.callBackResponse = JSON.stringify(JSON.parse(this.callBackResponse), null, 2);
      this.smsResponse = JSON.stringify(JSON.parse(this.smsResponse), null, 2);
      this.smsBackResponse = JSON.stringify(JSON.parse(this.smsBackResponse), null, 2);
      this.analysisResult = JSON.stringify(JSON.parse(this.analysisResult), null, 2);
      
      
      // 打开回调的弹窗
      this.callbackDialogVisible = true;
    },

    //导入号码
    importCallInfoBtn(){
      if (this.importCallInfoForm.toPhoneLine === ""){
        this.$message({
          showClose: true,
          message: "被叫号码不能为空",
          type: "error",
        });
        return;
      }
      this.importCallInfoForm.toPhoneList = this.importCallInfoForm.toPhoneLine.split("\n");
      this.importCallInfoForm.tableName = this.tableName;
      this.importCallInfoLoading = true;
      importCallInfo(this.importCallInfoForm).then((res) => {
        this.importCallInfoLoading = false;
        if (res.code === 0) {
          this.search();
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
          this.importCallInfoVisible = false;
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      })
    },
    //打开配置文件
    openFileBtn(fileType){
      openFile(fileType).then((res) => {
        if (res.code === 0) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      })
    },

    //批量删除
    batchDeleteBtn() {
      let ids = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((x) => {
          ids.push(x.id);
        });
      }
      if (ids.length < 1) {
        this.$message({
          showClose: true,
          duration: 0,
          message: "当前没有选择需要删除的数据!",
          type: "error",
        });
        return;
      }
      batchDelete({
        "tableName": this.tableName,
        "fieldName": "id",
        "fieldValueList": ids
      }).then((res) => {
        this.search();
        this.multipleSelection = [];
        this.$refs.multipleTable.clearSelection();
        this.$message({
          message: res.data,
          type: "success",
        });
      });
    },



  },
};
</script>
